package cm.cool.web.service;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cm.cool.web.bean.Admin;
import cm.cool.web.data.LoginMapper;
import cm.cool.web.util.cookie.CookieOp;
import cm.cool.web.util.date.TimeUtil;
import cm.cool.web.util.respon.R;
import cm.cool.web.util.respon.ResultEncoding;
import cm.cool.web.util.security.MD5;
import cm.cool.web.util.tokencache.TokenCacheMap;
import cm.cool.web.util.tokencache.TokenUtil;

@Service
public class LoginService {
	
	@Autowired
	LoginMapper loginMapper;
	
	@Value("${cookie.name}")
	private String cookieName;
	
	/**
	 * 管理员登录
	 * @param user
	 * @return
	 */
	public R login(Admin user,HttpServletResponse response){
		
		R r=new R();
		//数据验证
		if(R.isNull(user.getAccount()) ||  R.isNull(user.getAccount())){
			r.setData("用户名或密码为空");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}
		
		//请求数据
		Admin resultUser=null;
		
		//密码加密
		user.setPassword(MD5.EncoderByMd5(user.getPassword()));
		
		try {
			resultUser=loginMapper.login(user);
		} catch (Exception e) {
			System.out.println("登录异常=============="+e.getMessage());
		}
		//验证登录是否成功
		if(resultUser==null){
			r.setMsg("账号或者密码错误");
			r.setCode(ResultEncoding.R_PARAMETER);
			return r;
		}
		
		//登錄成功 生成token信息
		String token=resultUser.getId()+"_"+UUID.randomUUID()+"_"+resultUser.getAccount()+"_"+TimeUtil.getSecond();
		
		//將token信息存入到內存当中
		TokenCacheMap.addTokenList(resultUser.getId(), token);
		
		//判断获取的cookie名称 
		if(cookieName==null || cookieName.equals("")){
			cookieName="securityName";
		}
		
		//将token存入到cookie中
		if(CookieOp.setCookie(response, cookieName, token)){
			r.setMsg("登录成功");
		}
		return r;
	}
	
	
	/**
	 * 登出系统
	 * @param user
	 * @param response
	 * @return
	 */
	public R loginOut(Admin user ,HttpServletRequest request){
		R r=new R();
		
		try {
			 String tokenValue=CookieOp.getCookie(request, cookieName);
			 String uid=TokenUtil.getAdminId(tokenValue);
			 if(R.isNull(uid)){
				 r.setMsg("获取系统参数失败，登出错误");
				 r.setCode(ResultEncoding.R_PARAMETER);
				 return r;
			 }
			 TokenCacheMap.deleteTokenList(uid);
			 r.setMsg("登录成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return r;
	}
}
